package com.example.controller;

import com.example.common.Result;
import lombok.RequiredArgsConstructor;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * 测试控制器
 */
@RestController
@RequestMapping("/api/test")
@RequiredArgsConstructor
public class TestController {

    private final DataSource dataSource;
    private final JdbcTemplate jdbcTemplate;

    /**
     * 测试数据库连接
     */
    @GetMapping("/db")
    public Result<Map<String, Object>> testDatabase() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 测试数据源连接
            boolean isValid = dataSource.getConnection().isValid(5);
            result.put("connection", isValid ? "成功" : "失败");
            
            // 执行简单查询
            String dbVersion = jdbcTemplate.queryForObject("SELECT VERSION()", String.class);
            result.put("version", dbVersion);
            
            // 获取数据库名称
            String dbName = jdbcTemplate.queryForObject("SELECT DATABASE()", String.class);
            result.put("database", dbName);
            
            // 检查表是否存在
            Integer productCount = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = 'products'", 
                Integer.class);
            result.put("products_table_exists", productCount > 0);
            
            Integer contactFormsCount = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = 'contact_forms'", 
                Integer.class);
            result.put("contact_forms_table_exists", contactFormsCount > 0);
            
            return Result.success(result);
        } catch (Exception e) {
            result.put("error", e.getMessage());
            return Result.success(result);
        }
    }
} 